package egovframework.npqs.pqi.mobile.util;

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.net.URL;
import java.net.URLConnection;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import egovframework.npqs.pqi.mobile.common.Const;


//카메라에 필요한 메서드를 모아둔 클래스
//작성자     : 김준성
//개발일자   : 20150105
public class CameraUtil {
	
	private static CameraUtil instance = null;
	
	public synchronized static CameraUtil getInstance(){
		if(instance == null){
			synchronized (CameraUtil.class) {
				instance = new CameraUtil();
			}
		}
		return instance;
	}
	
	//서버에서 폴더 위치를 불러와서 Full Path 리턴
	public String photoSetting(String img){
		String url=Const.MAIN_URL;
		if("".equals(img)||null==img){
			return img;
		}else{
			url = url.replaceAll("/index.do","");
			url += img;
			return url;
		}
	}
	
	//웹에서 사진을 가지고와서 Drawable로 변환
	@SuppressWarnings("deprecation")
	public Drawable LoadImageFromWeb(String url){
		Bitmap imgBitmap = null;
		Drawable d = null;
	      try{
	    	  URL url2 = new URL(url);
	    	  URLConnection conn = url2.openConnection();
	    	  conn.connect();
	    	  int nSize = conn.getContentLength();
	    	  BufferedInputStream bis = new BufferedInputStream(conn.getInputStream(), nSize);
	    	  imgBitmap = BitmapFactory.decodeStream(bis);
	    	  bis.close();
	    	  d = new BitmapDrawable(imgBitmap);
	          return d;
	      }catch (Exception e) {
	          return null;
	      }
	}
	
	//디코딩 & 인코딩
	//프리잰테이션 측 : Bitmap -> Byte[]
	public byte[] bitmapToByteArray(Bitmap bitmap) {
		ByteArrayOutputStream stream = new ByteArrayOutputStream();
		bitmap.compress(CompressFormat.JPEG, 100, stream);
		byte[] byteArray = stream.toByteArray();
		return byteArray;
	}
	//프리잰테이션측 : byte[] -> String
	public String castByteArrayToString(byte[] barray){
		StringBuffer byteToString = new StringBuffer();
		for(int i=0; i<barray.length; i++){
			if(i==barray.length-1){
				byteToString.append(barray[i]);
			}else{
				byteToString.append(barray[i]+",");
			}
		}
		int i = byteToString.toString().length();
		return byteToString.toString();
	}
	//서버측 : String -> byte[]
	public byte[] castStringToByteArray(String str){
		String[] byteValues = str.substring(0, str.length()).split(",");
		byte[] bytes = new byte[byteValues.length];
		for (int i=0, len=bytes.length; i<len; i++) {
			   bytes[i] = Byte.valueOf(byteValues[i].trim());     
			}
		return bytes;
	}
	//서버 측 : byte[] -> Bitmap
	public Bitmap byteArrayToBitmap( byte[] byteArray ) {  
	    Bitmap bitmap = BitmapFactory.decodeByteArray( byteArray, 0, byteArray.length ) ;  
	    return bitmap ;  
	} 
}
